package com.example.hrsystem.ui.user;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.hrsystem.MainActivity;
import com.example.hrsystem.R;
import com.example.hrsystem.data.model.User;
import com.example.hrsystem.data.repository.UserRepository;

public class LoginActivity extends AppCompatActivity {

    private EditText phoneNumberEditText;
    private EditText passwordEditText;
    private Button loginButton;
    private Button registerButton;
    private UserRepository userRepository;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
            setContentView(R.layout.login_activity);

            // 初始化用户仓库
            try {
                userRepository = new UserRepository(getApplication());
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "初始化失败，请重启应用", Toast.LENGTH_SHORT).show();
            }

            // 检查是否已登录，如果已登录则直接跳转到首页
            try {
                if (isUserLoggedIn()) {
                    navigateToMainActivity();
                    finish();
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 初始化UI组件
            try {
                phoneNumberEditText = findViewById(R.id.phone_number_edit_text);
                passwordEditText = findViewById(R.id.password_edit_text);
                loginButton = findViewById(R.id.login_button);
                registerButton = findViewById(R.id.register_button);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "界面加载失败", Toast.LENGTH_SHORT).show();
            }

            // 设置登录按钮点击事件
            try {
                if (loginButton != null) {
                    loginButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            handleLogin();
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 设置注册按钮点击事件
            try {
                if (registerButton != null) {
                    registerButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 跳转到注册页面
                            try {
                                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(LoginActivity.this, "跳转失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "登录页面加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理登录逻辑
     */
    private void handleLogin() {
        try {
            if (phoneNumberEditText == null || passwordEditText == null) {
                Toast.makeText(this, "界面组件未初始化", Toast.LENGTH_SHORT).show();
                return;
            }

            String phoneNumber = phoneNumberEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString().trim();

            // 输入校验
            if (!isValidPhoneNumber(phoneNumber)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            }

            // 使用回调版本验证用户登录
            try {
                userRepository.authenticateUser(phoneNumber, password, new UserRepository.UserAuthenticateCallback() {
                    @Override
                    public void onResult(User user) {
                        try {
                            if (user != null) {
                                // 登录成功，保存登录状态
                                try {
                                    saveLoginState(user);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(LoginActivity.this, "保存用户信息失败", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    return;
                                }
                                // 跳转到首页
                                navigateToMainActivity();
                            } else {
                                // 登录失败，显示错误信息
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(LoginActivity.this, "手机号或密码错误", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(LoginActivity.this, "处理登录结果失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "发起登录请求失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "登录处理异常", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 验证手机号格式是否正确
     */
    private boolean isValidPhoneNumber(String phoneNumber) {
        // 简单的手机号格式校验，中国大陆手机号通常为11位数字
        return !TextUtils.isEmpty(phoneNumber) && phoneNumber.length() == 11 && phoneNumber.matches("[0-9]+");
    }

    /**
     * 保存登录状态
     */
    private void saveLoginState(User user) {
        try {
            if (user == null) {
                throw new IllegalArgumentException("User cannot be null");
            }
            SharedPreferences preferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("is_logged_in", true);
            editor.putString("phone_number", user.getPhoneNumber());
            editor.putString("user_id", String.valueOf(user.getUserId()));
            editor.putString("employee_id", user.getEmployeeId());
            editor.putString("name", user.getName());
            editor.apply();
        } catch (Exception e) {
            e.printStackTrace();
            throw e; // 重新抛出异常以便上层捕获
        }
    }

    /**
     * 检查用户是否已登录
     */
    private boolean isUserLoggedIn() {
        try {
            SharedPreferences preferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
            return preferences.getBoolean("is_logged_in", false);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 跳转到首页
     */
    private void navigateToMainActivity() {
        try {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            // 暂时移除页面切换动画，避免资源找不到的问题
            // overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            finish();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "跳转到首页失败", Toast.LENGTH_SHORT).show();
        }
    }
}